package com.example.demo.aqs;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangadmin
 */
public class ReentrantLockByBlockQueue<T> {

    /**
     * 阻塞队列最大容量
     */
    int size;

    ReentrantLock lock = new ReentrantLock(false);
    /**
     * 队列底层实现
     */
    LinkedList<T> list = new LinkedList<>();
    //
    /**
     * 队列满时的等待条件
     */
    Condition notFull = lock.newCondition();
    /**
     * 队列空时的等待条件
     */
    Condition notEmpty = lock.newCondition();

    public ReentrantLockByBlockQueue(int size) {
        this.size = size;
    }


    public void inQueue(T t) {
        lock.lock();
        try {
            while (list.size() == size) {
                notFull.await();
            }
            list.add(t);
            System.out.println("入队：" + t);
            //通知在notEmpty条件上等待的线程
            notEmpty.signal();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }

    }

    public T outQueue() {
        lock.lock();
        try {
            while (list.size() == 0) {
                notEmpty.await();
            }
            T t = list.removeFirst();
            System.out.println("出队：" + t);
            notFull.signal();
            return t;
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
        return null;
    }

    public static void main(String[] args) {
        ReentrantLockByBlockQueue<Integer> queue = new ReentrantLockByBlockQueue<>(2);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> queue.inQueue(finalI)).start();

        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> queue.outQueue()).start();
        }

    }
}
